[[...path]].page.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, isClient, isIPageInfoForEntity, IUser, IUserHasId, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import ExtensibleCustomError from 'extensible-custom-error';
  7. import { model as mongooseModel } from 'mongoose';
  8. import {
  9. NextPage, GetServerSideProps, GetServerSidePropsContext,
  10. } from 'next';
  11. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  12. import dynamic from 'next/dynamic';
  13. import Head from 'next/head';
  14. import { useRouter } from 'next/router';
  15. import superjson from 'superjson';
  16. // import { Comments } from '~/components/Comments';
  17. // import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  18. // import { useTranslation } from '~/i18n';
  19. // import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  20. // import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  21. import { CrowiRequest } from '~/interfaces/crowi-request';
  22. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  23. // import { useIndentSize } from '~/stores/editor';
  24. // import { useRendererSettings } from '~/stores/renderer';
  25. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  26. import { EditorConfig } from '~/interfaces/editor-settings';
  27. import { CustomWindow } from '~/interfaces/global';
  28. import { RendererConfig } from '~/interfaces/services/renderer';
  29. import { ISidebarConfig } from '~/interfaces/sidebar-config';
  30. import { IUserUISettings } from '~/interfaces/user-ui-settings';
  31. import { PageModel, PageDocument } from '~/server/models/page';
  32. import { PageRedirectModel } from '~/server/models/page-redirect';
  33. import { UserUISettingsModel } from '~/server/models/user-ui-settings';
  34. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  35. import { useRedirectFrom } from '~/stores/page-redirect';
  36. import {
  37. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth, useSelectedGrant,
  38. } from '~/stores/ui';
  39. import loggerFactory from '~/utils/logger';
  40. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  41. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  42. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  43. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  44. import { BasicLayout } from '../components/Layout/BasicLayout';
  45. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  46. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  47. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  48. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  49. import {
  50. useCurrentUser, useCurrentPagePath,
  51. useIsLatestRevision,
  52. useIsForbidden, useIsNotFound, useIsTrashPage, useIsSharedUser,
  53. useIsEnabledStaleNotification, useIsIdenticalPath,
  54. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  55. useDrawioUri, useHackmdUri,
  56. useIsAclEnabled, useIsUserPage,
  57. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  58. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  59. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage,
  60. } from '../stores/context';
  61. import {
  62. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  63. } from './utils/commons';
  64. // import { useCurrentPageSWR } from '../stores/page';
  65. // const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  66. // const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  67. // const UnsavedAlertDialog = dynamic(() => import('./UnsavedAlertDialog'), { ssr: false });
  68. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  69. // const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  70. // .then(mod => mod.UsersHomePageFooter), { ssr: false });
  71. const logger = loggerFactory('growi:pages:all');
  72. const {
  73. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  74. } = pagePathUtils;
  75. const { removeHeadingSlash } = pathUtils;
  76. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  77. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  78. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  79. {
  80. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  81. return v?.data != null
  82. && v?.data.toObject != null
  83. && v?.meta != null
  84. && isIPageInfoForEntity(v.meta);
  85. },
  86. serialize: (v) => {
  87. return {
  88. data: superjson.stringify(v.data.toObject()),
  89. meta: superjson.stringify(v.meta),
  90. };
  91. },
  92. deserialize: (v) => {
  93. return {
  94. data: superjson.parse(v.data),
  95. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  96. };
  97. },
  98. },
  99. 'IPageToShowRevisionWithMetaTransformer',
  100. );
  101. // const IdenticalPathPage = (): JSX.Element => {
  102. // const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  103. // return <IdenticalPathPage />;
  104. // };
  105. // const PutbackPageModal = (): JSX.Element => {
  106. // const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  107. // return <PutbackPageModal />;
  108. // };
  109. type Props = CommonProps & {
  110. currentUser: IUser,
  111. pageWithMeta: IPageToShowRevisionWithMeta | null,
  112. // pageUser?: any,
  113. redirectFrom?: string;
  114. // shareLinkId?: string;
  115. isLatestRevision?: boolean
  116. isIdenticalPathPage?: boolean,
  117. isForbidden: boolean,
  118. isNotFound: boolean,
  119. isNotCreatablePage: boolean,
  120. // isAbleToDeleteCompletely: boolean,
  121. isSearchServiceConfigured: boolean,
  122. isSearchServiceReachable: boolean,
  123. isSearchScopeChildrenAsDefault: boolean,
  124. isSlackConfigured: boolean,
  125. // isMailerSetup: boolean,
  126. isAclEnabled: boolean,
  127. // hasSlackConfig: boolean,
  128. drawioUri: string,
  129. hackmdUri: string,
  130. noCdn: string,
  131. // highlightJsStyle: string,
  132. isAllReplyShown: boolean,
  133. // isContainerFluid: boolean,
  134. editorConfig: EditorConfig,
  135. isEnabledStaleNotification: boolean,
  136. // isEnabledLinebreaks: boolean,
  137. // isEnabledLinebreaksInComments: boolean,
  138. // adminPreferredIndentSize: number,
  139. // isIndentSizeForced: boolean,
  140. disableLinkSharing: boolean,
  141. rendererConfig: RendererConfig,
  142. // UI
  143. userUISettings?: IUserUISettings
  144. // Sidebar
  145. sidebarConfig: ISidebarConfig,
  146. };
  147. const GrowiPage: NextPage<Props> = (props: Props) => {
  148. // const { t } = useTranslation();
  149. const router = useRouter();
  150. // const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  151. // register global EventEmitter
  152. if (isClient()) {
  153. (window as CustomWindow).globalEmitter = new EventEmitter();
  154. }
  155. // commons
  156. useEditorConfig(props.editorConfig);
  157. useCsrfToken(props.csrfToken);
  158. // UserUISettings
  159. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  160. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  161. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  162. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  163. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  164. // page
  165. useIsLatestRevision(props.isLatestRevision);
  166. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  167. useIsForbidden(props.isForbidden);
  168. useIsNotFound(props.isNotFound);
  169. // useIsNotCreatable(props.IsNotCreatable);
  170. useRedirectFrom(props.redirectFrom);
  171. // useShared();
  172. // useShareLinkId(props.shareLinkId);
  173. useIsSharedUser(false); // this page cann't be routed for '/share'
  174. useIsIdenticalPath(false); // TODO: need to initialize from props
  175. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  176. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  177. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  178. useIsSearchServiceReachable(props.isSearchServiceReachable);
  179. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  180. useIsSlackConfigured(props.isSlackConfigured);
  181. // useIsMailerSetup(props.isMailerSetup);
  182. useIsAclEnabled(props.isAclEnabled);
  183. // useHasSlackConfig(props.hasSlackConfig);
  184. useDrawioUri(props.drawioUri);
  185. useHackmdUri(props.hackmdUri);
  186. // useNoCdn(props.noCdn);
  187. // useIndentSize(props.adminPreferredIndentSize);
  188. useDisableLinkSharing(props.disableLinkSharing);
  189. useRendererConfig(props.rendererConfig);
  190. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  191. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  192. useIsAllReplyShown(props.isAllReplyShown);
  193. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  194. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  195. // const { data: editorMode } = useEditorMode();
  196. const { pageWithMeta, userUISettings } = props;
  197. useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  198. useEditingMarkdown(pageWithMeta?.data.revision?.body ?? '');
  199. const pageId = pageWithMeta?.data._id;
  200. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  201. useCurrentPageId(pageId ?? null);
  202. useIsUserPage(pagePath != null && isUserPage(pagePath));
  203. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  204. useCurrentPagePath(pagePath);
  205. useCurrentPathname(props.currentPathname);
  206. useIsTrashPage(pagePath != null && _isTrashPage(pagePath));
  207. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  208. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  209. // const shouldRenderPutbackPageModal = pageWithMeta != null
  210. // ? _isTrashPage(pageWithMeta.data.path)
  211. // : false;
  212. // sync grant data
  213. useEffect(() => {
  214. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  215. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  216. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  217. useEffect(() => {
  218. const decodedURI = decodeURI(window.location.pathname);
  219. if (isClient() && decodedURI !== props.currentPathname) {
  220. router.replace(props.currentPathname, undefined, { shallow: true });
  221. }
  222. }, [props.currentPathname, router]);
  223. const classNames: string[] = [];
  224. // switch (editorMode) {
  225. // case EditorMode.Editor:
  226. // classNames.push('on-edit', 'builtin-editor');
  227. // break;
  228. // case EditorMode.HackMD:
  229. // classNames.push('on-edit', 'hackmd');
  230. // break;
  231. // }
  232. // if (page == null) {
  233. // classNames.push('not-found-page');
  234. // }
  235. // const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  236. return (
  237. <>
  238. <Head>
  239. {/*
  240. {renderScriptTagByName('drawio-viewer')}
  241. {renderScriptTagByName('highlight-addons')}
  242. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  243. */}
  244. </Head>
  245. {/* <BasicLayout title={useCustomTitle(props, t('GROWI'))} className={classNames.join(' ')}> */}
  246. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={props.isContainerFluid}>
  247. <div className="h-100 d-flex flex-column justify-content-between">
  248. <header className="py-0 position-relative">
  249. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  250. </header>
  251. <div className="d-edit-none">
  252. <GrowiSubNavigationSwitcher />
  253. </div>
  254. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  255. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  256. <div className="flex-grow-1">
  257. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  258. <div id="content-main" className="content-main grw-container-convertible">
  259. {/* { props.isIdenticalPathPage && <IdenticalPathPage /> } */}
  260. { !props.isIdenticalPathPage && (
  261. <>
  262. {/* <PageAlerts /> */}
  263. {/* { props.isForbidden && <ForbiddenPage /> } */}
  264. {/* { props.isNotCreatablePage && <NotCreatablePage />} */}
  265. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  266. {/* <DisplaySwitcher /> */}
  267. {/* <PageStatusAlert /> */}
  268. </>
  269. ) }
  270. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  271. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  272. <div id="revision-toc-content" className="revision-toc-content"></div>
  273. </div>
  274. </div> */}
  275. </div>
  276. </div>
  277. </div>
  278. {/* { !props.isIdenticalPathPage && !props.isNotFound && (
  279. <footer className="footer d-edit-none">
  280. { pageWithMeta != null && !isTopPagePath && (<Comments pageId={pageId} revision={pageWithMeta.data.revision} />) }
  281. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  282. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  283. ) }
  284. <CurrentPageContentFooter />
  285. </footer>
  286. )} */}
  287. {/* <UnsavedAlertDialog /> */}
  288. {/* <DescendantsPageListModal /> */}
  289. {/* {shouldRenderPutbackPageModal && <PutbackPageModal />} */}
  290. </div>
  291. </BasicLayout>
  292. </>
  293. );
  294. };
  295. function getPageIdFromPathname(currentPathname: string): string | null {
  296. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  297. }
  298. class MultiplePagesHitsError extends ExtensibleCustomError {
  299. pagePath: string;
  300. constructor(pagePath: string) {
  301. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  302. this.pagePath = pagePath;
  303. }
  304. }
  305. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  306. const req: CrowiRequest = context.req as CrowiRequest;
  307. const { crowi } = req;
  308. const { revisionId } = req.query;
  309. const Page = crowi.model('Page') as PageModel;
  310. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  311. const { pageService } = crowi;
  312. let currentPathname = props.currentPathname;
  313. const pageId = getPageIdFromPathname(currentPathname);
  314. const isPermalink = _isPermalink(currentPathname);
  315. const { user } = req;
  316. if (!isPermalink) {
  317. // check redirects
  318. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  319. if (chains != null) {
  320. // overwrite currentPathname
  321. currentPathname = chains.end.toPath;
  322. props.currentPathname = currentPathname;
  323. // set redirectFrom
  324. props.redirectFrom = chains.start.fromPath;
  325. }
  326. // check whether the specified page path hits to multiple pages
  327. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  328. if (count > 1) {
  329. throw new MultiplePagesHitsError(currentPathname);
  330. }
  331. }
  332. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  333. const page = pageWithMeta?.data as unknown as PageDocument;
  334. // add user to seen users
  335. if (page != null && user != null) {
  336. await page.seen(user);
  337. }
  338. // populate & check if the revision is latest
  339. if (page != null) {
  340. page.initLatestRevisionField(revisionId);
  341. await page.populateDataToShowRevision();
  342. props.isLatestRevision = page.isLatestRevision();
  343. }
  344. props.pageWithMeta = pageWithMeta;
  345. }
  346. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  347. const req = context.req as CrowiRequest<IUserHasId & any>;
  348. const { user } = req;
  349. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  350. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  351. if (userUISettings != null) {
  352. props.userUISettings = userUISettings.toObject();
  353. }
  354. }
  355. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  356. const req: CrowiRequest = context.req as CrowiRequest;
  357. const { crowi } = req;
  358. const Page = crowi.model('Page') as PageModel;
  359. const { currentPathname } = props;
  360. const pageId = getPageIdFromPathname(currentPathname);
  361. const isPermalink = _isPermalink(currentPathname);
  362. const page = props.pageWithMeta?.data;
  363. if (props.isIdenticalPathPage) {
  364. // TBD
  365. }
  366. else if (page == null) {
  367. props.isNotFound = true;
  368. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  369. // check the page is forbidden or just does not exist.
  370. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  371. props.isForbidden = count > 0;
  372. }
  373. else {
  374. props.isNotFound = page.isEmpty;
  375. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  376. if (isPermalink && page.isEmpty) {
  377. props.currentPathname = page.path;
  378. }
  379. // /path/to/page ==> /62a88db47fed8b2d94f30000
  380. if (!isPermalink && !page.isEmpty) {
  381. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  382. if (!isToppage) {
  383. props.currentPathname = `/${page._id}`;
  384. }
  385. }
  386. }
  387. }
  388. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  389. // const req: CrowiRequest = context.req as CrowiRequest;
  390. // const { crowi } = req;
  391. // const UserModel = crowi.model('User');
  392. // if (isUserPage(props.currentPagePath)) {
  393. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  394. // if (user != null) {
  395. // props.pageUser = JSON.stringify(user.toObject());
  396. // }
  397. // }
  398. // }
  399. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  400. const req: CrowiRequest = context.req as CrowiRequest;
  401. const { crowi } = req;
  402. const {
  403. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  404. } = crowi;
  405. props.isSearchServiceConfigured = searchService.isConfigured;
  406. props.isSearchServiceReachable = searchService.isReachable;
  407. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  408. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  409. // props.isMailerSetup = mailService.isMailerSetup;
  410. props.isAclEnabled = aclService.isAclEnabled();
  411. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  412. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  413. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  414. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  415. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  416. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  417. // props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  418. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  419. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  420. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  421. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  422. props.editorConfig = {
  423. upload: {
  424. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  425. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  426. },
  427. };
  428. // props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  429. // props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  430. props.rendererConfig = {
  431. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  432. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  433. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  434. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  435. plantumlUri: process.env.PLANTUML_URI ?? null,
  436. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  437. // XSS Options
  438. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  439. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  440. tagWhiteList: crowi.xssService.getTagWhiteList(),
  441. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  442. };
  443. props.sidebarConfig = {
  444. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  445. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  446. };
  447. }
  448. /**
  449. * for Server Side Translations
  450. * @param context
  451. * @param props
  452. * @param namespacesRequired
  453. */
  454. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  455. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  456. props._nextI18Next = nextI18NextConfig._nextI18Next;
  457. }
  458. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  459. const req = context.req as CrowiRequest<IUserHasId & any>;
  460. const { user } = req;
  461. const result = await getServerSideCommonProps(context);
  462. // check for presence
  463. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  464. if (!('props' in result)) {
  465. throw new Error('invalid getSSP result');
  466. }
  467. const props: Props = result.props as Props;
  468. if (props.redirectDestination != null) {
  469. return {
  470. redirect: {
  471. permanent: false,
  472. destination: props.redirectDestination,
  473. },
  474. };
  475. }
  476. if (user != null) {
  477. props.currentUser = user.toObject();
  478. }
  479. try {
  480. await injectPageData(context, props);
  481. }
  482. catch (err) {
  483. if (err instanceof MultiplePagesHitsError) {
  484. props.isIdenticalPathPage = true;
  485. }
  486. else {
  487. throw err;
  488. }
  489. }
  490. await injectUserUISettings(context, props);
  491. await injectRoutingInformation(context, props);
  492. injectServerConfigurations(context, props);
  493. await injectNextI18NextConfigurations(context, props, ['translation']);
  494. return {
  495. props,
  496. };
  497. };
  498. export default GrowiPage;